<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="6" :xs="24">
        <div class="head-container">
          <el-input
            v-model="dataModels.deptName"
            placeholder="请输入部门名称"
            clearable
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :props="defaultProps"
            :expand-on-click-node="false"
            :highlight-current="true"
            :indent="20"
            ref="tree"
            @node-click="handleNodeClick"
            node-key="id"
            :load="loadNode"
            lazy
            draggable
            :allow-drop="allowDrop"
            :allow-drag="allowDrag"
            @node-drop="handleDrop"
            :filter-node-method="filterNode"
            style="border: 1px solid #ccc; border-radius: 4px; min-height: 500px;"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="18" :xs="24">
        <el-form :model="dataModels.department" v-show="dataModels.showDept">
          <el-row style="border-bottom: 1px solid #ddd;">
            <el-col :span="8">
              <h3>部门信息</h3>
            </el-col>
            <el-col :span="16" style="padding: 15px 0; text-align: right;">
              <el-button type="primary" icon="el-icon-circle-plus-outline" @click="addNewDept">添加部门</el-button>
              <el-button
                type="primary"
                icon="el-icon-circle-plus-outline"
                @click="showPosModel({ pageAction: 'create' })"
              >添加岗位</el-button>
              <el-button icon="el-icon-remove-outline" type="primary" @click="goEditDept">编辑</el-button>
              <el-button icon="el-icon-remove-outline" type="danger" @click="removeDept">删除</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="部门名称：" prop="name">
                <el-input v-model="dataModels.department.name" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门编码：" prop="code">
                <el-input v-model="dataModels.department.code" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="负责人" prop="manager">
                <el-input v-model="dataModels.department.manager" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否启用：" prop="isEnabled">
                <el-select v-model="dataModels.department.isEnabled" disabled>
                  <el-option :value="true" label="是"></el-option>
                  <el-option :value="false" label="否"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注：" prop="description">
                <el-input type="textarea" v-model="dataModels.department.description" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-form :model="dataModels.position" v-show="dataModels.showPosition">
          <el-row style="border-bottom: 1px solid #ddd;">
            <el-col :span="8">
              <h3>岗位信息</h3>
            </el-col>
            <el-col :span="16" style="padding: 15px 0; text-align: right;">
              <el-button
                icon="el-icon-remove-outline"
                type="success"
                @click="showPosModel({ pageAction: 'edit' })"
              >编辑</el-button>
              <el-button icon="el-icon-remove-outline" type="danger" @click="deletePos">删除</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="岗位名称：" prop="name">
                <el-input v-model="dataModels.position.name" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="岗位编码：" prop="code">
                <el-input v-model="dataModels.position.code" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div v-show="dataModels.showDept || dataModels.showPosition">
          <el-row style="border-bottom: 1px solid #ddd;">
            <el-col :span="8">
              <h3>人员信息</h3>
            </el-col>
            <el-col
              :span="16"
              style="padding: 15px 0; text-align: right;"
              v-show="dataModels.showPosition"
            >
              <el-button
                icon="el-icon-remove-outline"
                type="success"
                @click="selectUserModalVisible = true"
              >添加人员</el-button>
              <el-button icon="el-icon-remove-outline" type="danger" @click="removeUser">移除人员</el-button>
            </el-col>
          </el-row>

          <div class="searchBox" style="margin-bottom: 5px;">
            <el-form :inline="true" :model="dataModels.search" ref="searchForm">
              <el-form-item label="人员名称：" prop="USER_NAME">
                <el-input v-model="dataModels.search.USER_NAME" placeholder="请输入内容"></el-input>
              </el-form-item>
              <el-form-item label="登录账号：" prop="LOGIN_ID">
                <el-input v-model="dataModels.search.LOGIN_ID" placeholder="请输入内容"></el-input>
              </el-form-item>
              <el-form-item style="margin-top: -2px">
                <el-button type="primary" @click="$refs['qmTable'].fetchListData({ start:0 })">查询</el-button>
              </el-form-item>
            </el-form>
          </div>

          <qm-table
            ref="qmTable"
            :urls="tableUrls"
            :beforeQuery="beforeQuery"
            :showToolbar="false"
            :showMenu="false"
            :options="{ checkboxConfig: { highlight: true, trigger: 'row' } }"
          >
            <qm-table-column field="userName">姓名</qm-table-column>
            <qm-table-column field="loginId">登录账号</qm-table-column>
            <qm-table-column field="depName">所属部门</qm-table-column>
            <qm-table-column field="posName">岗位名称</qm-table-column>
          </qm-table>
        </div>
      </el-col>
    </el-row>

    <vxe-modal
      ref="posModal"
      v-model="posModels.posModalVisible"
      :resize="true"
      width="1024"
      height="300"
      :title="posModels.pageAction=='create'?'添加岗位':'编辑岗位'"
      :show-zoom="true"
      :destroy-on-close="true"
    >
      <el-form
        ref="posForm"
        :model="posModels.model"
        :rules="posModels.rules"
        labelWidth="100px"
        style="margin: 12px 6px 12px 0;"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位名称：" prop="name">
              <el-input v-model="posModels.model.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位编码：" prop="code">
              <el-input v-model="posModels.model.code"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位排序：" prop="sort">
              <el-input v-model="posModels.model.sort"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位类型：" prop="positionTypeId">
              <el-select v-model="posModels.model.positionTypeId">
                <el-option
                  v-for="option in posModels.controlData.positionTypes"
                  :key="option.positionTypeId"
                  :value="option.positionTypeId"
                  :label="option.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="text-align: right;">
          <el-button
            type="primary"
            :loading="posModels.saveLoading"
            @click="submitPosForm(posModels.pageAction)"
          >保 存</el-button>
          <el-button @click="posModels.posModalVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </vxe-modal>

    <set-users
      v-model="selectUserModalVisible"
      @success="afterSelectUser"
      @cancel="selectUserModalVisible = false"
      :onBeforeQuery="onBeforeQuery"
      :multiple="true"
    ></set-users>

    <create
      v-model="deptModels.deptModalVisible"
      :params="deptModels.addDeptUrlParams"
      @success="addDeptSuccess(deptModels.addDeptUrlParams.pageAction)"
      @cancel="deptModels.deptModalVisible = false"
    ></create>
  </div>
</template>

<script>
import Controller from "@/libs/framework/controller";
import request from "@/utils/request";
import _ from "lodash";
import SetUsers from "./setUsers";
import Create from "./create";

export default class Instance extends Controller {
  onBeforeInit() {
    this.urls = {
      model: "/admin/sysDepartment/getListModel",
      delete: "/admin/sysDepartment/delete",
    };
  }

  mixin() {
    return {
      components: {
        SetUsers,
        Create,
      },
      data() {
        return {
          defaultProps: {
            children: "childs",
            label: "text",
          },
          selectUserModalVisible: false,
          selectUserUrl: "/admin/sysDepartment/addUsers/query",

          deptModels: {
            deptModalVisible: false,
            model: {},
            controlData: {},
            addDeptUrlParams: {},
          },

          posModels: {
            posModalVisible: false,
            model: {},
            controlData: {},
            pageAction: "create",
            rules: {
              name: [
                {
                  required: true,
                  message: "请输入岗位名称",
                  trigger: "blur",
                },
              ],
              code: [
                {
                  required: true,
                  message: "请输入岗位编码",
                  trigger: "blur",
                },
              ],
            },
            saveLoading: false,
          },
          dataModels: {
            queryUrl: "",
            deptName: "",
            department: {},
            showDept: false,
            position: {},
            showPosition: false,
            search: {
              DEPARTMENT_ID: "",
              POSITION_ID: "",
              USER_NAME: "",
              LOGIN_ID: "",
            },
          },
        };
      },
      computed: {
        tableUrls() {
          return { query: this.dataModels.queryUrl };
        },
      },
      watch: {
        "dataModels.deptName"(val) {
          this.$refs.tree.filter(val);
        },
      },
      methods: {
        addDeptSuccess(page) {
          this.deptModels.deptModalVisible = false;
          let $tree = this.$refs["tree"];
          let item = $tree.getCurrentNode();
          if (page == "create") {
            $tree.getNode(item).loaded = false;
            $tree.getNode(item).expand();
          } else {
            $tree.getNode(item).parent.loaded = false;
            $tree.getNode(item).parent.expand();
            this.getDepartmentData(item.departmentId).then((dept) => {
              this.dataModels.department = dept || {};
              this.dataModels.position = {};
              this.dataModels.search.DEPARTMENT_ID = item.departmentId;
              this.dataModels.search.POSITION_ID = "";
              this.dataModels.queryUrl =
                "/admin/sysDepartment/departmentUser/query?_randomTime=" +
                new Date().getTime();
            });
          }
        },
        allowDrop(draggingNode, dropNode, type) {
          // 目标只能是部门
          return dropNode.data.id.startsWith("d");
        },
        allowDrag(draggingNode) {
          // 不是根元素都可以移动
          return draggingNode.data.id !== "root";
        },
        handleDrop(draggingNode, dropNode, dropType, ev) {
          let sourceId = draggingNode.data.id;
          let parentId = "";
          if (dropType === "inner") {
            parentId = dropNode.data.id;
          } else {
            parentId = dropNode.parent.data.id;
          }
          request({
            url: "/admin/sysDepartment/moveNode",
            method: "post",
            data: { sourceId: sourceId, parentId: parentId },
          }).then((r) => {
            if (r && r.success) {
              this.notifySuccess("移动成功");
            } else {
              this.notifyError(r.message || "移动失败,操作有误");
              const { fullPath } = this.$route;
              this.$router.replace({
                path: "/redirect" + fullPath,
              });
            }
          });
        },
        handleNodeClick(item, node, $node) {
          let id = item.id;
          if (id === "root") {
            this.dataModels.showDept = false;
            this.dataModels.showPosition = false;
            return;
          }
          if (id.startsWith("d")) {
            if (id.substr(1) === this.dataModels.department.departmentId) {
              return;
            }
            // 部门
            this.dataModels.showDept = true;
            this.dataModels.showPosition = false;
            this.getDepartmentData(id.substr(1)).then((dept) => {
              this.dataModels.department = dept || {};
              this.dataModels.position = {};
              this.dataModels.search.DEPARTMENT_ID = id.substr(1);
              this.dataModels.search.POSITION_ID = "";
              this.dataModels.queryUrl =
                "/admin/sysDepartment/departmentUser/query?_randomTime=" +
                new Date().getTime();
            });
          }
          if (id.startsWith("p")) {
            if (id.substr(1) === this.dataModels.position.positionId) {
              return;
            }
            // 岗位
            this.dataModels.showDept = false;
            this.dataModels.showPosition = true;
            this.getPositionData(id.substr(1)).then((pos) => {
              this.dataModels.position = pos || {};
              this.dataModels.department = {};
              this.dataModels.search.POSITION_ID = id.substr(1);
              this.dataModels.search.DEPARTMENT_ID = "";
              this.dataModels.queryUrl =
                "/admin/sysDepartment/positionUser/query?_randomTime=" +
                new Date().getTime();
            });
          }
        },
        filterNode(value, data) {
          if (!value) return true;
          return data.text.indexOf(value) !== -1;
        },
        loadNode(node, resolve) {
          let id = "#";
          if (node.data) {
            id = node.data.id;
          }
          // 异步加载子节点
          request({
            url: "/admin/sysDepartment/getChild",
            method: "get",
            params: { id: id },
          })
            .then((r) => {
              r.forEach((item) => {
                if (item.children) {
                  item.childs = [];
                }
                if (item.id !== "root") {
                  item.departmentId = item.id;
                }
              });
              resolve(r);
            })
            .catch((e) => {
              this.msgError("获取数据失败，请稍后再试");
            });
        },
        getDepartmentData(id) {
          return new Promise((rs, rj) => {
            request({
              url: "/admin/sysDepartment/get",
              method: "get",
              params: { id: id },
            })
              .then((r) => {
                rs(r);
              })
              .catch((e) => {
                this.msgError("获取部门信息失败，请稍后再试");
              });
          });
        },
        getPositionData(id) {
          return new Promise((rs, rj) => {
            request({
              url: "/admin/sysPosition/get",
              method: "get",
              params: { id: id },
            })
              .then((r) => {
                rs(r);
              })
              .catch((e) => {
                this.msgError("获取岗位信息失败，请稍后再试");
              });
          });
        },
        beforeQuery(params) {
          params.query = _.extend(params.query, this.dataModels.search);
        },
        showPosModel(params = {}) {
          let positionId = this.dataModels.position.positionId;
          this.getEntity(
            _.extend(
              {},
              { pageAction: "create", positionId: positionId || "" },
              params
            ),
            "/admin/sysPosition/getEntity"
          )
            .then((vm) => {
              this.posModels.model = vm.models.model;
              if (!this.posModels.model.departmentId) {
                this.posModels.model.departmentId =
                  this.dataModels.department.departmentId;
              }
              this.posModels.controlData = vm.controlData;
              this.posModels.posModalVisible = true;
              this.posModels.pageAction = vm.pageAction;
            })
            .catch((e) => {
              this.msgError(e.message || "获取数据失败，请稍后再试");
            });
        },
        submitPosForm(page) {
          let $tree = this.$refs["tree"];
          let item = $tree.getCurrentNode();
          this.$refs["posForm"].validate((valid) => {
            if (valid) {
              this.posModels.saveLoading = true;
              request({
                url: `/admin/sysPosition/save?positionId=${
                  this.posModels.model.positionId || ""
                }`,
                method: "post",
                data: {
                  model: this.posModels.model,
                  pageAction: this.posModels.pageAction,
                },
              })
                .then((r) => {
                  this.posModels.posModalVisible = false;
                  this.posModels.saveLoading = false;
                  if (page == "create") {
                    $tree.getNode(item).loaded = false;
                    $tree.getNode(item).expand();
                  } else {
                    this.getPositionData(item.id).then((pos) => {
                      this.dataModels.position = pos || {};
                      this.dataModels.department = {};
                      this.dataModels.search.POSITION_ID = item.id;
                      this.dataModels.search.DEPARTMENT_ID = "";
                      this.dataModels.queryUrl =
                        "/admin/sysDepartment/positionUser/query?_randomTime=" +
                        new Date().getTime();
                    });
                    $tree.getNode(item).parent.loaded = false;
                    $tree.getNode(item).parent.expand();
                  }
                })
                .catch((e) => {
                  this.posModels.saveLoading = false;
                  this.msgError(e.message || "操作执行出错，请稍后再试");
                });
            } else {
              console.log("error submit!!");
              return false;
            }
          });
        },
        deletePos() {
          let $tree = this.$refs["tree"];
          let item = $tree.getCurrentNode();
          let positionId = this.dataModels.position.positionId;
          if (!positionId) {
            return;
          }
          this.$confirm("确定删除嘛？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            request({
              url: "/admin/sysPosition/delete",
              method: "post",
              data: { delete: JSON.stringify([{ positionId: positionId }]) },
            }).then((r) => {
              if (r && r.success) {
                $tree.getNode(item).parent.loaded = false;
                $tree.getNode(item).parent.expand();
                this.dataModels.showDept = false;
                this.dataModels.showPosition = false;
                this.msgSuccess("删除成功");
              } else {
                this.msgError(r.message);
              }
            });
          });
        },

        removeUser() {
          let selectedRows = this.$refs["qmTable"].getSelectedRows();
          if (!selectedRows || !selectedRows.length) {
            this.msgError("请至少选中一项");
            return;
          }
          let postModel = [];
          selectedRows.forEach((item) => {
            postModel.push({ userId: item.userId });
          });
          this.$confirm("确定删除嘛？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              let positionId = this.dataModels.position.positionId;
              if (!positionId) {
                this.msgError("缺少岗位信息的相关参数！");
                return;
              }
              let loading = this.appLoading("正在删除...");
              request({
                url: "/admin/sysDepartment/removeByUserIds",
                method: "post",
                data: { delete: postModel, positionId: positionId },
              })
                .then((r) => {
                  loading.close();
                  this.msgSuccess("删除成功");
                  this.$refs["qmTable"].refresh();
                })
                .catch((e) => {
                  loading.close();
                });
            })
            .catch(() => {});
        },

        onBeforeQuery(params) {
          params.positionId = this.dataModels.position.positionId || "";
        },
        afterSelectUser(rows) {
          if (!rows || !rows.length) {
            return;
          }
          let positionId = this.dataModels.position.positionId || "";
          request({
            url: "/admin/sysDepartment/addUsers/save",
            method: "post",
            data: { requestJson: rows, positionId: positionId },
          })
            .then((r) => {
              this.selectUserModalVisible = false;
              this.$refs["qmTable"].refresh();
            })
            .catch((e) => {
              this.selectUserModalVisible = false;
            });
        },

        addNewDept() {
          let deptId = this.dataModels.department.departmentId;
          let rootId = this.dataModels.department.rootId;

          this.deptModels.addDeptUrlParams = {
            parentId: deptId,
            rootId: rootId,
            pageAction: "create",
          };
          this.deptModels.deptModalVisible = true;
        },
        goEditDept() {
          let deptId = this.dataModels.department.departmentId;
          this.deptModels.addDeptUrlParams = {
            departmentId: deptId,
            pageAction: "edit",
          };
          this.deptModels.deptModalVisible = true;
        },
        removeDept() {
          let $tree = this.$refs["tree"];
          let item = $tree.getCurrentNode();
          let deptId = this.dataModels.department.departmentId;
          if (!deptId) {
            this.msgError("主键为空，操作失败");
            return;
          }
          this.$confirm("确认删除该部门吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              let loading = this.appLoading("正在删除...");
              request({
                url: "/admin/sysDepartment/delete",
                method: "post",
                data: { delete: JSON.stringify([{ departmentId: deptId }]) },
              })
                .then((r) => {
                  loading.close();
                  if (r && r.success) {
                    $tree.getNode(item).parent.loaded = false;
                    $tree.getNode(item).parent.expand();
                    this.dataModels.showDept = false;
                    this.dataModels.showPosition = false;
                    this.msgSuccess("删除成功");
                  } else {
                    this.msgError(r.message);
                  }
                })
                .catch((e) => {});
            })
            .catch(() => {});
        },
      },
    };
  }
}
</script>

<style scoped lang="scss">
</style>

